package com.yt.product.api.client;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.common.utils.StrUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import com.yt.product.models.service.IProductInfoService;
import com.yt.product.models.bo.ProductInfoBO;
import com.yt.product.models.bo.ProductInfoSaveBO;
import com.yt.product.models.dto.ProductInfoDTO;
import com.yt.product.models.vo.ProductInfoVO;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/productInfo")
@Slf4j
@Api(value = "ProductInfoApiController", tags = "产品信息Api接口")
public class ProductInfoApiController {

    @DubboReference
    private IProductInfoService productInfoService;

    // 新增产品
    @ApiOperation(value = "新增产品", notes = "新增产品信息")
    @PostMapping("/add")
    public Result<ProductInfoVO> add(@RequestBody ProductInfoSaveBO saveBO) {
        boolean success = productInfoService.add(saveBO);
        if (success) {
            // 查询刚插入的记录
            ProductInfoDTO dto = productInfoService.selectOne(
                    new EntityWrapper<ProductInfoDTO>()
                            .eq("product_name", saveBO.getProductName())
                            .eq("category_id", saveBO.getCategoryId())
                            .orderBy("create_time", false)
                            .last("LIMIT 1")
            );
            if (dto == null) {
                return new Result<>(CodeEnum.FAIL_100010);
            }
            return new Result<>(convertToVO(dto));
        }
        return new Result<>(CodeEnum.FAIL_100007);
    }

    // 更新产品
    @ApiOperation(value = "更新产品", notes = "根据ID更新产品信息")
    @PutMapping("/update/{id}")
    public Result<ProductInfoVO> update(
            @PathVariable Long id,
            @RequestBody ProductInfoSaveBO saveBO) {

        // 校验记录是否存在
        ProductInfoDTO existingDto = productInfoService.selectById(id);
        if (existingDto == null) {
            return new Result<>(CodeEnum.FAIL_100010);
        }

        // 复制更新字段
        ProductInfoDTO updateDto = new ProductInfoDTO();
        BeanUtils.copyProperties(saveBO, updateDto);
        updateDto.setId(id);
        updateDto.setUpdateTime(new Date()); // 更新时间戳

        boolean success = productInfoService.updateById(updateDto);
        if (success) {
            return new Result<>(convertToVO(productInfoService.selectById(id)));
        }
        return new Result<>(CodeEnum.FAIL_100008);
    }

    // 物理删除产品
    @ApiOperation(value = "删除产品", notes = "物理删除产品信息")
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        // 校验记录是否存在
        if (productInfoService.selectById(id) == null) {
            return new Result<>(CodeEnum.FAIL_100010);
        }
        boolean success = productInfoService.deleteById(id);
        return success ? new Result<>() : new Result<>(CodeEnum.FAIL_100009);
    }

    // 查询单条产品
    @ApiOperation(value = "查询产品详情", notes = "根据ID查询产品详情（含供应商和分类名称）")
    @ApiImplicitParam(name = "id", value = "产品ID", required = true, paramType = "path", dataType = "Long")
    @GetMapping("/get/{id}")
    public Result<ProductInfoVO> get(@PathVariable Long id) {
        if (id == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        ProductInfoVO vo = productInfoService.selectVoById(id);
        if (vo == null) {
            return new Result<>(CodeEnum.FAIL_100010);
        }

        return new Result<>(vo);
    }


    @ApiOperation(value = "查询产品列表（分页）", notes = "查询所有产品列表（含供应商和分类名称，支持分页）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "页码（默认1）", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数（默认10）", paramType = "query", dataType = "Integer")
    })
    @GetMapping("/list")
    public Result<Page<ProductInfoVO>> list(
            ProductInfoBO bo,
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        // 构建分页对象（泛型为VO）
        Page<ProductInfoVO> page = new Page<>(pageNo, pageSize);

        // 调用Service的分页查询方法（返回Page<ProductInfoVO>）
        Page<ProductInfoVO> voPage = productInfoService.selectVoPage(page, bo);

        return new Result<>(voPage);
    }

    @ApiOperation(value = "按名称模糊查询产品（分页）", notes = "根据产品名称模糊查询匹配结果")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productName", value = "产品名称（模糊匹配）", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "pageNo", value = "页码（默认1）", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数（默认10）", paramType = "query", dataType = "Integer")
    })
    @GetMapping("/searchByName")
    public Result<Page<ProductInfoVO>> searchByName(
            String productName,
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        if (StrUtils.isEmpty(productName)) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        Page<ProductInfoVO> page = new Page<>(pageNo, pageSize);

        ProductInfoBO bo = new ProductInfoBO();
        bo.setProductName(productName);

        Page<ProductInfoVO> voPage = productInfoService.selectVoPage(page, bo);

        return new Result<>(voPage);
    }

    @ApiOperation(value = "按类目名称模糊查询产品（分页）", notes = "根据产品类目名称模糊查询所属产品（含分页参数）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryName", value = "类目名称（模糊匹配）", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "pageNo", value = "页码（默认1）", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数（默认10）", paramType = "query", dataType = "Integer")
    })
    @GetMapping("/searchByCategoryName")
    public Result<Page<ProductInfoVO>> searchByCategoryName(
            String categoryName,
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        if (StrUtils.isEmpty(categoryName)) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        Page<ProductInfoVO> page = new Page<>(pageNo, pageSize);

        ProductInfoBO bo = new ProductInfoBO();
        bo.setCategoryName(categoryName);

        Page<ProductInfoVO> voPage = productInfoService.selectVoByCategoryNamePage(page, bo);

        return new Result<>(voPage);
    }

    private ProductInfoVO convertToVO(ProductInfoDTO dto) {
        if (dto == null) {
            return null;
        }
        ProductInfoVO vo = new ProductInfoVO();
        BeanUtils.copyProperties(dto, vo);
        return vo;
    }
}